package com.chrray.position.controller.util;

import com.chrray.position.service.upload.UploadrService;
import com.chrray.position.util.result.ResponseResult;
import com.google.common.collect.Sets;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.compress.utils.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.AntPathMatcher;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.HandlerMapping;

import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.Set;


/**
 * @author li'miao
 */
@Controller
@RequestMapping("/api")
@Api(value = "上传文件",tags = "上传文件")
@Slf4j
public class UploadImgController {

    @Autowired
   private UploadrService uploadrService;
    /**
     * 编辑器上传图片
     * @param upload
     * @return
     * @throws Exception
     */
    @PostMapping(value = "/upload/upload-file")
    @ResponseBody
    @ApiOperation(value = "上传文件，返回地址（通用）")
    public ResponseResult uploadPic(@RequestParam("file") MultipartFile upload)  {

        return  uploadrService.uploadPic(upload);

    }


    private static final Set<String> IMG_SUFFIX = Sets.newHashSet("jpg", "jpeg", "png", "gif", "bmp", "webp");
    /**
     * 文件下载
     */
    @RequestMapping("/download/**")
    @ApiOperation(value = "文件下载")
    public void download( HttpServletResponse response) throws IOException {
        String path = (String) RequestContextHolder.getRequestAttributes()
                .getAttribute(HandlerMapping.PATH_WITHIN_HANDLER_MAPPING_ATTRIBUTE, RequestAttributes.SCOPE_REQUEST);
        String bestMatchPattern = (String) RequestContextHolder.getRequestAttributes()
                .getAttribute(HandlerMapping.BEST_MATCHING_PATTERN_ATTRIBUTE, RequestAttributes.SCOPE_REQUEST);

        String fileId = File.separator+new AntPathMatcher().extractPathWithinPattern(bestMatchPattern, path);
        try (InputStream object = uploadrService.getImg(fileId); OutputStream outputStream = response.getOutputStream()) {

            response.reset();
            response.addHeader("Access-Control-Allow-Origin", "*");
            response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileId, StandardCharsets.UTF_8.name()));
            String suffix = getSuffix(fileId);
            if (IMG_SUFFIX.contains(suffix)) {
                response.setContentType("image/" + suffix);
            } else if ("pdf".equalsIgnoreCase(suffix)) {
                response.setContentType("application/pdf");
            } else if ("doc".equalsIgnoreCase(suffix) || "docx".equalsIgnoreCase(suffix)) {
                response.setContentType("application/msword");
            } else if ("xls".equalsIgnoreCase(suffix) || "xlsx".equalsIgnoreCase(suffix)) {
                response.setContentType("application/vnd.ms-excel");
            } else if ("ppt".equalsIgnoreCase(suffix) || "pptx".equalsIgnoreCase(suffix)) {
                response.setContentType("application/vnd.ms-powerpoint");
            } else if ("txt".equalsIgnoreCase(suffix)) {
                response.setContentType("text/plain");
            } else {
                response.setContentType("application/octet-stream");
            }
            response.setCharacterEncoding("UTF-8");
            // 输出文件
            IOUtils.copy(object, outputStream);

        } catch (Exception e) {
            response.setHeader("Content-type", "text/html;charset=UTF-8");
            String data = "文件不存在";
            OutputStream ps = response.getOutputStream();
            ps.write(data.getBytes(StandardCharsets.UTF_8));
        }
        // 关闭输出流

    }

    private String getSuffix(String fileId) {
        return fileId.indexOf(".") != -1 ? (fileId.substring(fileId.lastIndexOf(".") + 1, fileId.length())) : null;
    }


}
